import { z } from "zod";

export const ClearinghouseAssetPositionSchema = z.object({
  position: z.object({
    coin: z.string(),
    cumFunding: z.object({
      allTime: z.string(),
      sinceChange: z.string(),
      sinceOpen: z.string(),
    }),
    entryPx: z.string(),
    leverage: z.object({
      type: z.string(),
      value: z.number(),
    }),
    liquidationPx: z.string().nullable(),
    marginUsed: z.string(),
    maxLeverage: z.number(),
    positionValue: z.string(),
    returnOnEquity: z.string(),
    szi: z.string(),
    unrealizedPnl: z.string(),
  }),
  type: z.string(),
});

export type ClearinghouseAssetPosition = z.infer<
  typeof ClearinghouseAssetPositionSchema
>;

export const ClearinghouseStateSchema = z.object({
  marginSummary: z.object({
    accountValue: z.string(),
    totalNtlPos: z.string(),
    totalRawUsd: z.string(),
    totalMarginUsed: z.string(),
  }),
  crossMarginSummary: z.object({
    accountValue: z.string(),
    totalNtlPos: z.string(),
    totalRawUsd: z.string(),
    totalMarginUsed: z.string(),
  }),
  crossMaintenanceMarginUsed: z.optional(z.string()),
  withdrawable: z.string(),
  assetPositions: z.array(ClearinghouseAssetPositionSchema),
  time: z.optional(z.number()),
});

export type ClearinghouseState = z.infer<typeof ClearinghouseStateSchema>;

export const SpotClearinghouseBalanceSchema = z.object({
  coin: z.string(),
  token: z.optional(z.number()),
  hold: z.string(),
  total: z.string(),
  entryNtl: z.string(),
});

export type SpotClearinghouseBalance = z.infer<
  typeof SpotClearinghouseBalanceSchema
>;

export const SpotClearinghouseStateSchema = z.object({
  balances: z.array(SpotClearinghouseBalanceSchema),
});

export type SpotClearinghouseState = z.infer<
  typeof SpotClearinghouseStateSchema
>;

export const HyperliquidPortfolioOverviewSchema = z.object({
  spotBalances: SpotClearinghouseStateSchema,
  perpBalances: ClearinghouseStateSchema,
});

export type HyperliquidPortfolioOverview = z.infer<
  typeof HyperliquidPortfolioOverviewSchema
>;

export const FilledStatusSchema = z.object({
  totalSz: z.string(),
  avgPx: z.string(),
  oid: z.number(),
});

export const OrderStatusSchema = z.object({
  filled: FilledStatusSchema,
});

export const OrderDataSchema = z.object({
  statuses: z.array(OrderStatusSchema),
});

export const OrderResponseSchema = z.object({
  type: z.literal("order"),
  data: OrderDataSchema,
});

export const MarketOpenResponseSchema = z.object({
  status: z.literal("ok"),
  response: OrderResponseSchema,
});

export type MarketOpenResponse = z.infer<typeof MarketOpenResponseSchema>;
